package com.yizhubao.app;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.FrameLayout;

import androidx.core.app.ActivityCompat;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tendcloud.tenddata.TCAgent;
import com.weikaiyun.fragmentation.SupportFragment;
import com.yizhubao.app.activitys.WebActivity;
import com.yizhubao.app.activitys.release.ReleaseActivity;
import com.yizhubao.app.app.YZBApp;
import com.yizhubao.app.base.BaseActivity;
import com.yizhubao.app.base.BaseResultBean;
import com.yizhubao.app.beans.ConfigBean;
import com.yizhubao.app.beans.WXLoginBean;
import com.yizhubao.app.customviews.BottomDialog;
import com.yizhubao.app.customviews.inter.CompleteCallBack;
import com.yizhubao.app.customviews.inter.OthersCallBack;
import com.yizhubao.app.events.LoginEvent;
import com.yizhubao.app.fragments.HomeFragment;
import com.yizhubao.app.fragments.SearchFragment;
import com.yizhubao.app.fragments.UserFragment;
import com.yizhubao.app.models.ConfigModel;
import com.yizhubao.app.models.WXLoginModel;
import com.yizhubao.app.utils.ConfigObserver;
import com.yizhubao.app.utils.Constants;
import com.yizhubao.app.utils.Utils;
import com.yizhubao.app.utils.net.BaseObserver;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import butterknife.BindView;
import h.framework.pacy.utils.LogUtil;
import h.framework.pacy.utils.PreferencesUtil;
import h.framework.pacy.utils.ToastUtil;
import h.framework.pacy.views.bottombar.BottomBarCheckTab;
import h.framework.pacy.views.bottombar.BottomCheckBar;

/**
 * 创建人: PACY
 * 创建时间: 6/4/21 9:59 AM
 * 邮箱: pengwwe457621023@qq.com
 * 类描述: main
 */
public class MainActivity extends BaseActivity {
    @BindView(R.id.bottomCheckBar)
    BottomCheckBar mBottomCheckBar; //底部bar
    @BindView(R.id.frame_fl)
    FrameLayout frameFl; //fragment显示

    public static final int FIRST = 0;
    public static final int SECOND = 1;
    public static final int THIRD = 2;

    private SupportFragment[] mFragments = new SupportFragment[3];


    WXLoginModel loginModel;
    boolean isRun = false;

    ConfigModel model;

    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;
    private static Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    protected void initView() {
        initFragments();
        initBottomCheckBar();
        LogUtil.i((String) PreferencesUtil.get(Constants.USER_ID, ""));
        TCAgent.LOG_ON=YZBApp.getInstance().isDebug;
        TCAgent.init(this);
        TCAgent.setReportUncaughtExceptions(true);
        //腾讯X5初始化
//        HashMap map = new HashMap();
//        map.put(TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER, true);
//        map.put(TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE, true);
//        QbSdk.initTbsSettings(map);
    }

    @Override
    protected void initData() {
        if(YZBApp.api==null){
            regToWx();
        }
        loginModel = new WXLoginModel();
        model = new ConfigModel();
        sendRequest();
    }

    /**
     * 注册微信
     */
    private void regToWx(){
        LogUtil.i("微信注册");
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        YZBApp.api = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID, true);
        // 将应用的appId注册到微信
        YZBApp.api.registerApp(Constants.WX_APP_ID);

        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // 将应用的appId注册到微信
                YZBApp.api.registerApp(Constants.WX_APP_ID);
            }
        },new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));
    }
    Handler handler = new Handler();
    void sendRequest() {
        model.getConfig(new ConfigObserver() {
            @Override
            public void onSuccess(ConfigBean t) {
               if(t.isShowOpenPopup()){
                   handler.postDelayed((Runnable) () -> {
                       BottomDialog.DialogBuilder(MainActivity.this).title(t.getOpenPopupConfig().getTitle()).message(t.getOpenPopupConfig().getContent())
                               .cancleText("关闭").othersCallBack(() -> {

                       }).completeText(t.getOpenPopupConfig().getConfirmBtnText()).completeCallBack(() -> {
                           Bundle bundle = new Bundle();
                           bundle.putString("title", "广告");
                           bundle.putString("url", t.getOpenPopupConfig().getConfirmBtnLink());
                           startActivity(MainActivity.this, WebActivity.class, bundle);
                       }).show();
                   },2000);
               }

            }

            @Override
            public void onError(String errMessage) {

            }
        }, getLifeSubject());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
//        if (getIntent().getExtras() != null) {
//            Bundle bundle = getIntent().getExtras();
//            isRun = bundle.getBoolean("isRun");
//        }
//        if (isRun) {
//            sendUserRequest();
//        }
    }

    /**
     * 获取用户信息
     */
    private void sendUserRequest() {
        loginModel.getUser(new BaseObserver<WXLoginBean>() {
            @Override
            public void onSuccess(BaseResultBean<WXLoginBean> t) {
                LogUtil.i("获取用户信息" + t.getData().toString());
                Utils.saveUser(t.getData());
                EventBus.getDefault().post(new LoginEvent());
            }

            @Override
            public void onError(String errMessage) {
                LogUtil.i("获取用户信息" + errMessage);
            }
        }, lifecycleSubject);
    }

    //初始化fragment
    private void initFragments() {
        mFragments[FIRST] = HomeFragment.newInstance("首页");
        mFragments[SECOND] = SearchFragment.newInstance("查询");
        mFragments[THIRD] = UserFragment.newInstance("我的");
        loadMultipleRootFragment(R.id.frame_fl, 0,
                mFragments[FIRST],
                mFragments[SECOND],
                mFragments[THIRD]);
    }

    /**
     * 两套图片  icon切换
     */
    private void initBottomCheckBar() {
        mBottomCheckBar
                .addItem(new BottomBarCheckTab(MainActivity.this, R.drawable.home_tab_bg, "首页"))
                .addItem(new BottomBarCheckTab(MainActivity.this, R.drawable.search_tab_bg, "查询"))
                .addItem(new BottomBarCheckTab(MainActivity.this, R.drawable.user_tab_bg, "我的"));
        // 模拟未读消息
//        mBottomCheckBar.getItem(2).setUnreadCount(9);
        mBottomCheckBar.setOnTabSelectedListener(new BottomCheckBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position, int prePosition) {
                showHideFragment(mFragments[position]);
                LogUtil.i("点击事件");
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {
                // 这里推荐使用EventBus来实现 -> 解耦
                // 主要为了交互: 重选tab 如果列表不在顶部则移动到顶部,如果已经在顶部,则刷新
            }
        });

    }


    /**
     * 处理回退事件
     *
     * @return
     */
    @Override
    public void onBackPressedSupport() {
        exit();
    }


    /**
     * 退出APP
     */
    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastUtil.showShort("再按一次退出");
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            YZBApp.getInstance().exit();
        }
    }

    @Override
    protected int setContentLayout() {
        return R.layout.activity_main;
    }
}